<template>
  <div class="home-container">
    <h1>灰度图像自动上色系统</h1>
    
    <div v-if="!isProcessing && !colorizedImage">
      <image-upload @colorization-start="handleColorization" />
    </div>
    
    <div v-if="isProcessing" class="processing-container">
      <el-progress
        type="circle"
        :percentage="processingProgress"
        :status="processingProgress === 100 ? 'success' : ''"
      />
      <p>正在处理中，请稍候...</p>
    </div>
    
    <div v-if="colorizedImage">
      <image-comparison
        :original-image="originalImage"
        :colorized-image="colorizedImage"
      />
      <div class="action-buttons">
        <el-button type="primary" @click="downloadImage">下载结果</el-button>
        <el-button @click="resetProcess">重新上传</el-button>
      </div>
    </div>

    <!-- 模型选择下拉菜单 -->
    <div class="model-selector" v-if="models.length > 0">
      <h3>选择上色模型</h3>
      <el-select v-model="selectedModel" placeholder="选择模型" @change="changeModel">
        <el-option 
          v-for="model in models" 
          :key="model" 
          :label="model.split('/').pop()" 
          :value="model">
        </el-option>
      </el-select>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import ImageUpload from '../components/ImageUpload.vue'
import ImageComparison from '../components/ImageComparison.vue'
import { colorizeImage, getAvailableModels, setModel } from '../api'
import type { ApiResponse, ModelsResponse, ColorizeResponse } from '../api'

const isProcessing = ref(false)
const processingProgress = ref(0)
const originalImage = ref('')
const colorizedImage = ref('')
const resultId = ref('')
const models = ref<string[]>([])
const selectedModel = ref('')

// 获取可用的模型
onMounted(async () => {
  try {
    const response = await getAvailableModels()
    if (response.success && response.models) {
      models.value = response.models
      if (models.value.length > 0) {
        selectedModel.value = models.value[0]
      }
    }
  } catch (error) {
    console.error('获取模型列表失败:', error)
  }
})

// 更改使用的模型
const changeModel = async (modelPath: string) => {
  const loading = ElLoading.service({
    lock: true,
    text: '切换模型中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    const response = await setModel(modelPath)
    if (response.success) {
      ElMessage.success('模型切换成功')
    } else {
      ElMessage.error('模型切换失败')
    }
  } catch (error) {
    ElMessage.error('模型切换失败，请重试')
    console.error('切换模型失败:', error)
  } finally {
    loading.close()
  }
}

// 处理上色请求
const handleColorization = async (data: { originalImage: string, file: File }) => {
  originalImage.value = data.originalImage
  const file = data.file
  
  isProcessing.value = true
  processingProgress.value = 0
  
  // 启动进度条动画
  const interval = setInterval(() => {
    if (processingProgress.value < 90) {
      processingProgress.value += 5
    }
  }, 200)
  
  try {
    const response = await colorizeImage(file)
    
    // 停止进度条动画并设置为100%
    clearInterval(interval)
    processingProgress.value = 100
    
    if (response.success) {
      setTimeout(() => {
        isProcessing.value = false
        resultId.value = response.id
        colorizedImage.value = `data:image/jpeg;base64,${response.image}`
        
        // 保存到历史记录
        saveToHistory(originalImage.value, colorizedImage.value)
      }, 500)
    } else {
      throw new Error('上色失败')
    }
  } catch (error) {
    clearInterval(interval)
    isProcessing.value = false
    ElMessage.error('上色失败，请重试')
    console.error('上色失败:', error)
  }
}

// 下载上色后的图片
const downloadImage = () => {
  if (!colorizedImage.value) return
  
  const link = document.createElement('a')
  link.href = colorizedImage.value
  link.download = `colorized_${resultId.value || Date.now()}.jpg`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 保存到历史记录
const saveToHistory = (original: string, colorized: string) => {
  const history = JSON.parse(localStorage.getItem('colorizeHistory') || '[]')
  
  // 添加新记录到开头
  history.unshift({
    id: resultId.value || Date.now().toString(),
    originalImage: original,
    colorizedImage: colorized,
    date: new Date().toISOString()
  })
  
  // 最多保存20条记录
  const limitedHistory = history.slice(0, 20)
  localStorage.setItem('colorizeHistory', JSON.stringify(limitedHistory))
}

const resetProcess = () => {
  isProcessing.value = false
  processingProgress.value = 0
  originalImage.value = ''
  colorizedImage.value = ''
  resultId.value = ''
}
</script>

<style scoped>
.home-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  text-align: center;
  margin-bottom: 40px;
}

.processing-container {
  text-align: center;
  padding: 40px;
}

.action-buttons {
  text-align: center;
  margin-top: 20px;
}

.model-selector {
  margin-top: 40px;
  text-align: center;
  padding: 20px;
  border-top: 1px solid #eee;
}

.model-selector h3 {
  margin-bottom: 15px;
}
</style> 